這個範例展示如何在 ES5 和 ES6 中使用動態的變數當作物件的屬性名稱。
var key = "person name"; // 宣告一個變數
var person = {}; // 建立一個空物件
person[key] = "Chris"; // 使用中括號設定屬性,key 是變數(值為 "person name")
person["person age"] = 21; // 傳統字串屬性
console.log(person[key]); // 印出 Chris
console.log(person["person name"]); // 也印出 Chris
let key = "person name"; // 宣告變數
let person = {
[key]: "Chris", // 使用 ES6 計算屬性名稱語法,直接用變數當屬性名
"person age": 21
};
console.log(person[key]); // 印出 Chris
console.log(person["person name"]); // 也印出 Chris